#include "HttpServer.hpp"
#include "Protocol.hpp"

#include <memory>

using namespace std;
using namespace server;

void Usage(std::string proc)
{
    std::cerr << "Usage:\n\t" << proc << " port\r\n";
}

string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg";
    ct += "\r\n";
    return ct;
}
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    cout << "----------------------http start------------------------" << endl;
    cout << req.inbuffer << endl;
    cout << "method:" << req.method << endl;
    cout << "url:" << req.url << endl;
    cout << "httpversion: " << req.httpversion << endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    cout << "----------------------http end--------------------------" << endl;

    string respline = "HTTP/1.1 200 OK\r\n";
    string respheader = suffixToDesc(req.suffix);
    if (req.size > 0)
    {
        respheader += "Content-Length:";
        respheader += to_string(req.size);
        respheader += "\r\n";
    }

    string respblank = "\r\n";
    string body;
    body.resize(req.size + 1);
    if (!Util::readFile(req.path, (char *)body.c_str(), req.size))
    {
        Util::readFile(html_404, (char *)body.c_str(), req.size);
    }

    resp.outbuffer += body;

    return true;
}

// ./httpServer 8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<HttpServer> httpsvr(new HttpServer(Get, port));

    httpsvr->initServer();
    httpsvr->start();

    return 0;
}